<?php
/**
 * Created by PhpStorm.
 * User: YongX
 * Date: 2018/1/7
 * Time: 19:14
 */

use App\Models\User;
use App\Models\Users\Role;

if (!function_exists('checkRole')) {

    /**
     * 对比交涉相关权限
     *
     * @param Role $role
     * @param Role $targetRole
     * @param string $permission
     * @return bool
     */
    function checkRole(Role $role, Role $targetRole, string $permission)
    {
        if ($role->hasPermission($permission) && $targetRole->hasPermission($permission)) {
            if ($role->flag < $targetRole->flag) {
                return false;
            }
        }
        return true;
    }
    if (function_exists('checkUserRole') === false) {
        /**
         * 检查用户权限
         *
         * @param User $user
         * @param User $target
         * @param string $permission
         * @return bool
         */
        function checkUserRole (User $user, User $target, string $permission) {
            $roles = $user->roles;
            $targetRoles = $target->roles;
            foreach ($roles as $role) {
                foreach ($targetRoles as $targetRole) {
                    if (checkRole($targetRole, $role, $permission) === false) {
                        return false;
                    }
                }
            }
            return true;
        }
    }
}
